package com.example.messengerapp.ui

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.messengerapp.R
import com.example.messengerapp.databinding.FragmentEditProfileBinding
import com.example.messengerapp.viewmodel.EditProfileViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser

class EditProfileFragment : Fragment() {

    companion object {
        private const val PICK_IMAGE_REQUEST = 1
    }

    private var _binding: FragmentEditProfileBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: EditProfileViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentEditProfileBinding.inflate(inflater, container, false)
        viewModel = ViewModelProvider(this).get(EditProfileViewModel::class.java)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val user = FirebaseAuth.getInstance().currentUser

        user?.let {
            displayUserInfo(it)
        }

        binding.saveButton.setOnClickListener {
            saveProfileData()
        }

        binding.editProfileImageView.setOnClickListener {
            openGallery()
        }

        binding.phoneIconImageView.setOnClickListener {
            showPhoneDialog()
        }

        viewModel.profileImageUri.observe(viewLifecycleOwner) { uri ->
            uri?.let {
                binding.profileImageView.setImageURI(it)
            }
        }
    }

    private fun displayUserInfo(user: FirebaseUser) {
        binding.userNameTextView.text = "Name: ${user.displayName}"
        binding.userEmailTextView.text = "Email: ${user.email}"
        binding.userLoginMethodTextView.text = "Login Method: Email" // Simplified for example
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
            val imageUri = data.data
            viewModel.updateProfileImage(imageUri!!)
        }
    }

    private fun showPhoneDialog() {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_phone_input, null)
        val phoneEditText = dialogView.findViewById<EditText>(R.id.phoneEditText)
        val countrySpinner = dialogView.findViewById<Spinner>(R.id.countrySpinner)
        val applyPhoneButton = dialogView.findViewById<Button>(R.id.applyPhoneButton)

        val countries = listOf("+1", "+44", "+91") // Example country codes
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, countries)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        countrySpinner.adapter = adapter

        val dialog = AlertDialog.Builder(context)
            .setTitle("Enter Phone Number")
            .setView(dialogView)
            .create()

        applyPhoneButton.setOnClickListener {
            val phone = "${countrySpinner.selectedItem}${phoneEditText.text.toString().trim()}"
            // Handle phone input
            Toast.makeText(context, "Phone: $phone", Toast.LENGTH_SHORT).show()
            dialog.dismiss() // Dismiss the dialog after applying the phone number
        }

        dialog.show()
    }

    private fun saveProfileData() {
        val name = binding.nameEditText.text.toString().trim()
        val surname = binding.surnameEditText.text.toString().trim()
        val username = binding.usernameEditText.text.toString().trim()
        val address = binding.adressEditText.text.toString().trim()
        val age = binding.ageEditText.text.toString().trim()

        if (name.isEmpty() || surname.isEmpty() || username.isEmpty() || address.isEmpty() || age.isEmpty()) {
            Toast.makeText(context, "Please fill in all fields", Toast.LENGTH_SHORT).show()
            return
        }

        val userProfile = UserProfile(name, surname, username, address, age)

        viewModel.saveUserProfile(userProfile) { success ->
            if (success) {
                viewModel.profileImageUri.value?.let { uri ->
                    viewModel.uploadProfileImage(uri) { downloadUri ->
                        if (downloadUri != null) {
                            Toast.makeText(context, "Profile updated successfully", Toast.LENGTH_SHORT).show()
                            activity?.finish()
                        } else {
                            Toast.makeText(context, "Failed to upload profile image", Toast.LENGTH_SHORT).show()
                        }
                    }
                } ?: run {
                    Toast.makeText(context, "Profile updated successfully", Toast.LENGTH_SHORT).show()
                    activity?.finish()
                }
            } else {
                Toast.makeText(context, "Failed to update profile", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    data class UserProfile(
        val name: String,
        val surname: String,
        val username: String,
        val address: String,
        val age: String
    )
}
